package cn.signalpha.modules.shop.wrapper;

import cn.signalpha.common.constant.MsgConstant;
import cn.signalpha.core.mp.support.BaseEntityWrapper;
import cn.signalpha.core.tool.jackson.JsonUtil;
import cn.signalpha.core.tool.utils.*;
import cn.signalpha.modules.com.entity.User;
import cn.signalpha.modules.com.service.UserService;
import cn.signalpha.modules.shop.entity.Order;
import cn.signalpha.modules.shop.entity.SellerAddress;
import cn.signalpha.modules.shop.entity.UserAddress;
import cn.signalpha.modules.shop.service.OrderDetailService;
import cn.signalpha.modules.shop.service.OrderLogisticsService;
import cn.signalpha.modules.shop.service.SellerService;
import cn.signalpha.modules.shop.vo.OrderDeliveryVO;
import cn.signalpha.modules.shop.vo.OrderVO;

import java.util.Objects;

/**
 * 包装类,返回视图层所需的字段
 */
public class OrderWrapper extends BaseEntityWrapper<Order, OrderVO> {

	private static final UserService userService;
    private static final SellerService sellerService;
    private static final OrderDetailService orderDetailService;
	private static final OrderLogisticsService orderLogisticsService;

	static {
		userService = SpringUtil.getBean(UserService.class);
        sellerService = SpringUtil.getBean(SellerService.class);
        orderDetailService = SpringUtil.getBean(OrderDetailService.class);
		orderLogisticsService = SpringUtil.getBean(OrderLogisticsService.class);
	}

	public static OrderWrapper build() {
		return new OrderWrapper();
	}

	@Override
	public OrderVO entityVO(Order order) {
        OrderVO orderVO = Objects.requireNonNull(BeanUtil.copy(order, OrderVO.class), MsgConstant.OBJECT_NULL);
		orderVO.setSeller(SellerWrapper.build().entityVO(sellerService.getById(orderVO.getSellerId())));

		User user = userService.getBaseById(orderVO.getUserId());
		if(ObjectUtil.isNotEmpty(user)){
			orderVO.setUserAvatar(user.getAvatar());
			orderVO.setUserNickName(user.getNickName());
			orderVO.setUserMobile(user.getMobile());
		}

		if(StringUtil.isNotBlank(orderVO.getLogisticsInfo())){
			orderVO.setLogistics(JsonUtil.parse(orderVO.getLogisticsInfo(), UserAddress.class));
		}
		if(StringUtil.isNotBlank(orderVO.getLogisticsSellerInfo()) && !StringPool.EMPTY_JSON.equals(orderVO.getLogisticsSellerInfo())){
			orderVO.setLogisticsSeller(JsonUtil.parse(orderVO.getLogisticsSellerInfo(), SellerAddress.class));
		}
		if(StringUtil.isNotBlank(orderVO.getLogisticsDeliveryInfo()) && !StringPool.EMPTY_JSON.equals(orderVO.getLogisticsDeliveryInfo())){
			orderVO.setOrderDeliveryVO(JsonUtil.parse(orderVO.getLogisticsDeliveryInfo(), OrderDeliveryVO.class));
		}
        orderVO.setOrderDetailList(orderDetailService.listByOrderNo(orderVO.getOrderNo()));
		orderVO.setOrderLogisticsList(orderLogisticsService.listByOrderNo(orderVO.getOrderNo()));
		return orderVO;
	}

}
